const express = require('express')
const path = require('path')
const fs = require('fs')
const moment = require('moment')
const router = express.Router()
let persons = fs.readFileSync('persons.json', 'utf8')
persons = JSON.parse(persons)

router.use(express.urlencoded({ extended: false }))

router.post('/loginp', (req, res, next) => {
    let { tel, pass } = req.body
    tel = tel.trim()
    pass = pass.trim()

    if(!tel || !pass){
        return
    }

    let tag = persons.find((item) => tel === item.tel && pass === item.pass)
    if (tag) {
        next('登录成功')
    } else {
        next('用户名和密码不匹配')
    }
})
router.post('/resisterp', (req, res, next) => {
    let { tel, pass, pass2 } = req.body
    tel = tel.trim()
    pass = pass.trim()
    pass2 = pass2.trim()
    if(!tel || !pass){
        return
    }
    let tag = persons.find((item) =>item.tel === tel)
    if (!tag) {
        if (pass === pass2) {
            let time = moment().format('YYYY年MM月DD日, hh:mm:ss')
            let obj = { tel, pass, time }
            persons.push(obj)
            fs.writeFileSync('persons.json', JSON.stringify(persons))
            next('注册成功')
            return
        } else {
            next('密码输入不一致')
            return
        }
    } else {
        next('用户名已存在')
        return
    }
})
router.use((err,req,res,next)=>{
    res.send(` <h2>${err}</h2>`)
})

module.exports = router